package com.zhao.fishingguideserver.service.impl;

import com.zhao.fishingguideserver.POJO.Cart;
import com.zhao.fishingguideserver.mapper.CartMapper;
import com.zhao.fishingguideserver.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private CartMapper cartMapper;

    // CartServiceImpl.java
    @Override
    public String addCart(Long userId, Long productId, Integer quantity) {
        Cart existing = cartMapper.selectByUserIdAndProductId(userId, productId);
        if (existing != null) {
            // 商品已存在：更新数量，返回“数量更新”提示
            existing.setQuantity(existing.getQuantity() + quantity);
            cartMapper.updateById(existing);
            return "商品已在购物车，数量已更新为" + existing.getQuantity();
        } else {
            // 商品不存在：新增，返回“添加成功”提示
            Cart cart = new Cart();
            cart.setUserId(userId);
            cart.setProductId(productId);
            cart.setQuantity(quantity);
            cart.setIsSelected(true);
            cartMapper.insert(cart);
            return "商品添加购物车成功";
        }
    }

    public List<Cart> listCart(Long userId) {
        return cartMapper.selectByUserId(userId);
    }

    public void updateQuantity(Long cartId, Integer quantity) {
        Cart cart = cartMapper.selectById(cartId);
        if (cart != null) {
            cart.setQuantity(quantity);
            cartMapper.updateById(cart);
        }
    }

    public void deleteCart(Long cartId) {
        cartMapper.deleteById(cartId);
    }

    public void toggleSelect(Long cartId, boolean isSelected) {
        Cart cart = cartMapper.selectById(cartId);
        if (cart != null) {
            cart.setIsSelected(isSelected);
            cartMapper.updateById(cart);
        }
    }

    public void selectAll(Long userId, boolean isSelected) {
        List<Cart> carts = cartMapper.selectByUserId(userId);
        for (Cart cart : carts) {
            cart.setIsSelected(isSelected);
        }
        cartMapper.updateBatchById(carts);
    }
    public void batchDelete(List<Long> cartIds) {
        cartMapper.deleteBatchIds(cartIds);
    }
}